<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<?php
$capitale=0;
$numRate=0;
$tan=0;
$esegui = isset($_POST['esegui'])?$_POST['esegui']:false;

// legge parametri
if(isset($_POST['capitale']))
	$capitale = is_numeric(htmlentities($_POST['capitale']))?htmlentities($_POST['capitale']):0 ;
if(isset($_POST['numRate']))
	$numRate = is_numeric(htmlentities($_POST['numRate']))?htmlentities($_POST['numRate']):0 ;
if(isset($_POST['tan']))
	$tan = is_numeric(htmlentities($_POST['tan']))?htmlentities($_POST['tan']):0 ;

// validazione input
$
$esegui = $esegui && ($capitale>0) && ($tan>0) ;

function rigaRata($n , $residuo, $capResiduo, $rata  , $interessi , $capitale  ){
	
	printf("<tr><td>%d</td>", $n);
	printf("<td>€%s</td>", number_format($residuo, 2));
	printf("<td>€%s</td>", number_format($capResiduo, 2));
	printf("<td>€%s</td>", number_format($rata, 2));
	printf("<td>€%s</td>", number_format($interessi, 2));
	printf("<td>€%s</td></tr>", number_format($capitale, 2));
}

?>
<h1>Piano di Ammortamento</h1>

<form action="" method="post">
	<fieldset>
		<legend> parametri</legend>
		<label>Capitale<input type="text" name="capitale" id="capitale"/></label>
		<label>Tan<input type="text" name="tan" id="tan"/></label>
		<label>NumeroRate<input type="text" name="numRate" id ="numRate"/></label>
		<label><input type="submit" name="Calcola" /> </label>
		<input type="hidden" name="esegui" value="true"/> 
	</fieldset>		
</form>

<?php

if($esegui){
	$tasso = $tan/1200;
	$rata = round( (1+(1/(pow((1+$tasso),$numRate)-1)))*$tasso*$capitale ,2);
	$montante = $rata*$numRate;
	$interessi = $montante - $capitale;
	$montanteCalc = round($capitale*pow((1+$tasso*12),$numRate/12),2);
	echo "<p>Capitale = $capitale</p>";
	echo "<p>Tan = $tan</p>";
	echo "<p>Num rate = $numRate</p>";
	echo "<p>Rata = $rata</p>";
	echo "<p>Montante calcolato ??= $montanteCalc</p>";
	echo "<p>Montante = $montante</p>";
	echo "<p>Interessi = $interessi</p>";
	
	$debitoResiduo = $montante;
	$interessiResidui = $interessi;
	$capitaleResiduo = $capitale;
	// Create table
	echo "<table width='60%' align='center' border='1'>";
	echo "<tr>
	<th>Numero rata</th><th>Debito residuo</th><th>Capitale residuo</th>
	<th>Pagamento</th><th>Interessi</th><th>Capitale</th>
	</tr>";
	for($i=0;$i<$numRate;$i++){
		$debitoResiduo = $debitoResiduo - $rata;
		$interessiRata = $capitaleResiduo * $tasso;
		$capitaleRata = $rata - $interessiRata;
		$interessiResidui = $interessiResidui - $interessiRata;
		$capitaleResiduo = $debitoResiduo -$interessiResidui;
		
		rigaRata($i+1,$debitoResiduo,$capitaleResiduo,$rata,$interessiRata,$capitaleRata);
	}
	// Close table
	echo "</table>";
}
?>
</body></html>